<template>
  <view class="invite">
    <img class="invite-img" src="https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/yaoqing.png" alt="">
    <view class="invite-box" v-if="isAuth">
      <view class="invite-box-item" v-for="(item, index) in arr1" :key="index">
        <view class="invite-box-item-left">0{{index + 1}}</view>
        <view class="invite-box-item-right" v-html="item.txt"></view>
      </view>
      <!--  #ifdef H5 -->
       <view class="invite-title">我的邀请码</view>
       <view style="text-align: center;width: 100%;height: 100rpx;font-size: 40rpx;color: #fff;">
         <text>{{userInfo.my_invite_code}}</text>
       </view>
      <!--   #endif -->
      <!--  #ifdef MP-WEIXIN -->
      <view class="invite-title">我的邀请二维码</view>
      <view style="text-align: center;width: 100%;height: 210rpx">
        <img v-if="qrcode" class="invite-qrcode" :src="qrcode"  :show-menu-by-longpress="true" @tap="previewImage" alt="">
        <view class="invite-second">长按发送给朋友就可以绑定推荐关系啦～</view>
      </view>
       <!--   #endif -->
      <view class="invite-btns">
        <!-- #ifdef MP -->
        <view class="invite-btns-item" @tap="saveQRcodeFn">保存二维码</view>
        <button style="border-radius: 100px;
        background: linear-gradient(180deg, #FBEB69 0%, #FCD44A 49.67%, #FDB221 100%);
        color: #AB6401;margin: 0" class="invite-btns-item" open-type="share">邀请新用户</button>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <view style="width: 100%" class="invite-btns-item" @click="copyUrl">复制地址，邀请新用户</view>
        <!-- #endif -->
      </view>
    </view>
    <!-- #ifdef MP -->
      <view class="invite-btn" v-else @tap="goLogin">
        登录获取用户信息
      </view>
    <!-- #endif -->
    <!-- #ifdef H5 -->
    <view class="invite-btn" v-else @tap="goLoginPage">
      登录获取用户信息
    </view>
    <!-- #endif -->
    <uni-popup ref="popup" type="top">
      <user-login :encryptedKey="encryptedKey" :inviteCode="inviteCode"></user-login>
    </uni-popup>
  </view>
</template>

<script>
  import userLogin from '../../components/userlogin/userlogin.vue'
  import myfn from '../../common/function/myPubFunction.js'
  export default {
    data() {
      return {
        arr1: [],
        encryptedKey: '',
        isChecked: false,
        userInfo: {},
        qrcode: '', // 小程序二维码  路径   邀请码
        isAuth: false,
        inviteCode: ''
      }
    },
    components: {
      userLogin
    },
    async onShareAppMessage(options) {
    	if (options.from === "menu") {
    		console.log(1111);
    	}
    	return {
    		title: "邀请您加入城市车位",
    		path: "/pages/index/index?invite_code=" + this.userInfo.my_invite_code,
    		imageUrl: "https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/2023/09/01/zhihuitingche.png",
    	};
    },
    onUnload() {
      uni.$off('loginSuccess')
    },
    onLoad(options) {
      uni.$on('loginSuccess', () => {
       vk.userCenter.getCurrentUserInfo({
         success: (data) => {
           // 成功后的逻辑
           vk.setVuex('$user.userInfo', data.userInfo)
           this.userInfo = data.userInfo
            this.isAuth = vk.checkToken()
            //#ifdef MP-WEIXIN
              this.getInviteQrcode()
            //#endif
            this.$refs.popup.close()
         }
       });
      })
      this.isAuth = vk.checkToken()
      this.userInfo = vk.getVuex('$user.userInfo')
      if (this.isAuth) {
        //#ifdef MP-WEIXIN
          this.getInviteQrcode()
          console.log(898989)
        //#endif
      }
      this.getBonus()
      //#ifdef MP-WEIXIN
        this.getKey()
      //#endif
    },
    methods: {
      copyUrl() {
        uni.setClipboardData({
        	data: 'https://tingche.nangua.website/h5?invite_code=' + this.userInfo.my_invite_code,
        	success: function () {
        		console.log('success');
        	}
        });

        myfn.uniCopy({
          content: 'https://tingche.nangua.website/h5?invite_code=' + this.userInfo.my_invite_code,
          success: (res) => {
            uni.showToast({
              title: '复制成功',
              icon: 'none'
            });
          },
          error: (e) => {
            console.log(e)
            uni.showToast(e);
          },
        });
      },
      getKey() {
        let that = this;
        vk.userCenter.code2SessionWeixin({
          data: {
            needCache: true
          },
          success: (data) => {
            that.encryptedKey = data.encryptedKey;
          },
        });
      },
      previewImage(e) {
        uni.previewImage({
          // 需要预览的图片链接列表。若无需预览，可以注释urls
          urls: [e.target.src], // 为当前显示图片的链接/索引值
          current: e.target.src, // 图片指示器样式	
          indicator: 'default', // 是否可循环预览
          loop: false, // 长按图片显示操作菜单，如不填默认为保存相册// 
          longPressActions: {
            // 	itemList:[this.l('发送给朋友'),this.l]// 
          },
          success: res => {
            console.log('previewImage res', res);
          },
          fail: err => {
            console.log('previewImage err', err);
          }
        });
      },
      saveBase64ImageToPhotosAlbum() {
        let that = this
        var timestamp = new Date().getTime();
        let base64 = this.qrcode.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
        let filePath = wx.env.USER_DATA_PATH + `/addFriends_${timestamp}_qrcode.png`;
        uni.showLoading({
          title: '保存中',
          mask: true
        })
        uni.getFileSystemManager().writeFile({
          filePath: filePath, //创建一个临时文件名
          data: base64, //写入的文本或二进制数据
          encoding: 'base64', //写入当前文件的字符编码
          success: res => {
            uni.saveImageToPhotosAlbum({
              filePath: filePath,
              success: function(res2) {
                uni.hideLoading();
                vk.toast('保存成功', 'none')
              },
              fail: function(err) {
                uni.hideLoading();
                console.log(err.errMsg);
                vk.toast('保存失败', 'none')
              }
            })
          },
          fail: err => {
            uni.hideLoading();
            console.log(err)
            vk.toast('创建文件失败', 'none')
          }
        })
      },
      saveQRcodeFn() { //保存图片到相册按钮的点击事件函数
        let that = this
        uni.getSetting({
          success(res) {
            console.log(res);
            if (!res.authSetting['scope.writePhotosAlbum']) {
              uni.authorize({
                scope: 'scope.writePhotosAlbum',
                success(res) {
                  that.saveBase64ImageToPhotosAlbum()
                },
                fail() {
                  uni.showModal({
                    content: '请允许相册权限,拒绝将无法正常保存图片',
                    showCancel: false,
                    success() {
                      uni.openSetting({
                        success(settingdata) {
                          if (settingdata.authSetting['scope.writePhotosAlbum']) {} else {
                            console.log('获取权限失败')
                            vk.toast('获取权限失败', 'none')
                          }
                        }
                      })
                    }
                  })
                }
              })
            } else {
              that.saveBase64ImageToPhotosAlbum()
            }
          }
        })
      },
      goLogin() {
        this.inviteCode = uni.getStorageSync('invite_code')
        this.$refs.popup.open()
      },
      goLoginPage() {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      },
      getInviteQrcode() {
        console.log(this.userInfo.my_invite_code, 'this.userInfo.my_invite_code----')
        vk.callFunction({
          url: 'user/kh/inviteQrcode',
          data: {
            page: 'pages/index/index',
            scene: 'invite_code=' + this.userInfo.my_invite_code
          },
          success: (res) => {
            this.qrcode = res.base64
          }
        })
      },
      getBonus() {
        uni.showLoading({
          title: '加载中...'
        })
        vk.callFunction({
          url: 'user/pub/bonusSetList',
          success: (res) => {
            console.log(res, 'res---')
            let obj = res.rows
            if(res.rows.length > 0) {
              for (let i=0; i< res.rows.length;i++) {
                let obj = res.rows[i]
                if (obj.first) {
                  this.arr1.unshift({
                    txt: `VIP级别及以上直接邀请用户注册并兑换,  立获${obj.relate_coupon_name + obj.first}%推荐积分`
                  })
                }
                if (obj.second) {
                  this.arr1.push({
                    txt: `VIP级别及以上间接邀请用户注册并兑换,  立获${obj.relate_coupon_name + obj.second}%推荐积分`
                  })
                }
              }
            }
            uni.hideLoading()
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .invite {
    position: relative;
    width: 100vw;
    height: 100vh;

    &-img {
      width: 750rpx;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
    }

    &-title {
      text-align: center;
      font-family: PingFang SC;
      font-size: 30rpx;
      font-style: normal;
      font-weight: 600;
      color: #fff;
      margin: 24rpx 0;
    }
    &-second {
      text-align: center;
      font-family: PingFang SC;
      font-size: 20rpx;
      font-style: normal;
      font-weight: 600;
      color: #fff;
      margin: 24rpx 0;
    }

    &-qrcode {
      width: 210rpx;
      height: 210rpx;
    }

    &-btns {
      margin-top: 120rpx;
      display: flex;
      width: 700rpx;
      justify-content: space-between;

      &-item {
        width: 320rpx;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        border-radius: 100px;
        background: linear-gradient(180deg, #FBEB69 0%, #FCD44A 49.67%, #FDB221 100%);
        color: #AB6401;
        text-align: center;
        font-family: PingFang SC;
        font-size: 34rpx;
        font-style: normal;
        font-weight: 600;
      }
    }

    &-box {
      position: absolute;
      z-index: 2;
      left: 50%;
      transform: translateX(-50%);
      top: 300rpx;

      &-item {
        display: flex;
        margin-bottom: 24rpx;
        border-radius: 4px;
        width: 700rpx;
        height: 150rpx;
        box-shadow: 0px 4px 20px 0px #FF2E00;

        &-left {
          background: linear-gradient(226deg, rgba(255, 111, 0, 0.90) 0%, rgba(255, 49, 0, 0.90) 100%);
          width: 150rpx;
          height: 150rpx;
          text-align: center;
          line-height: 150rpx;
          color: #FFF;
          font-size: 100rpx;
          font-style: normal;
          font-weight: 700;
        }

        &-right {
          background: linear-gradient(226deg, rgba(253, 141, 55, 0.90) 0%, rgba(255, 94, 56, 0.90) 100%);
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #FFF;
          font-family: PingFang SC;
          font-size: 26rpx;
          font-style: normal;
          font-weight: 400;
        }
      }
    }

    &-btn {
      position: absolute;
      z-index: 2;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      color: #fff;
      background-color: #005ECD;
      border-radius: 100rpx;
      width: 660rpx;
      height: 66rpx;
      text-align: center;
      line-height: 66rpx;
      font-family: PingFang SC;
      font-size: 32rpx;
      font-style: normal;
      font-weight: 600;
    }
  }
</style>